package com.tencent.basic.controller;

import com.tencent.basic.dto.SmsCodeDto;
import com.tencent.basic.exception.BusinessException;
import com.tencent.basic.service.IVerifyCodeService;
import com.tencent.basic.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/verifyCode")
public class VerifyCodeController {

    @Autowired
    private IVerifyCodeService verifyCodeService;

    @GetMapping("/image/{key}")
    public AjaxResult image(@PathVariable("key") String key){
        try {
            // 获取64位图形验证码，即64位编码字符串
            String code64 = verifyCodeService.image(key);
            // 将获得的编码响应给前端
            return AjaxResult.me().setResultObj(code64);
        } catch (Exception e) {
            e.printStackTrace();
            // 失败则返回失败原因
            return new AjaxResult(false, "获取图形码失败");
        }
    }


    // verifyCode/smsCode
    @PostMapping("/smsCode")
    public AjaxResult smsCode(@RequestBody SmsCodeDto smsCodeDto){
        try {
            verifyCodeService.smsCode(smsCodeDto);
            return new AjaxResult();
        } catch (BusinessException e) {
            e.printStackTrace();
            // 失败则返回失败原因
            return new AjaxResult(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            // 失败则返回失败原因
            return new AjaxResult(false, "获取手机验证码失败");
        }
    }

    @PostMapping("/binderSmsCode")
    public AjaxResult binderSmsCode(@RequestBody SmsCodeDto smsCodeDto){
        try {
            verifyCodeService.binderSmsCode(smsCodeDto);
            return new AjaxResult();
        } catch (BusinessException e) {
            e.printStackTrace();
            // 失败则返回失败原因
            return new AjaxResult(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            // 失败则返回失败原因
            return new AjaxResult(false, "获取手机验证码失败");
        }
    }
}
